package uploadAPI

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go-gin-init/app/models/enum"
	"go-gin-init/app/models/model"
	"go-gin-init/app/models/req"
	"go-gin-init/app/service"
	"go-gin-init/common/result"
	"go-gin-init/common/tool"
	"go-gin-init/common/xerr"
	"go.uber.org/zap"
)

// UploadExcel
// @Summary 上传excel
// @Description
// @Tags POST
// @Accept json
// @Produce json
// @Param Param body req.PostUpdateReq true "请求参数"
// @Success 200 {object} result.JsonResult "{"code":200,"data":{},"msg":"SUCCESS"}"
// @Failure 400 {object} result.JsonResult "{"code":200,"data":{},"msg":""}"
// @Failure 500 {string} string "Internal Server Error"
// @Router /post/update [post]
func UploadExcel(c *gin.Context) {

	var u req.UploadExcelReq
	err := c.ShouldBind(&u)
	if err != nil {
		result.ParamErrorResult(c, err)
		return
	}

	ExcelEnum := enum.GetExcelEnum(u.UploadType)
	if ExcelEnum == nil {
		result.ParamErrorResult(c, errors.New("上传类型不存在"))
		return
	}

	file, err := c.FormFile("excel")
	if err != nil || file == nil {
		result.ParamErrorResult(c, errors.New("上传文件不存在"))
		return
	}

	// 保存上传的文件到服务器
	fileName := "../../../uploads/excel" + file.Filename
	err = c.SaveUploadedFile(file, fileName)
	if err != nil {
		zap.L().Error("")
		result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
		return
	}

	fieldIdxMap := tool.InitTag2FieldIdx(ExcelEnum, "xlsx")

	// 默认sheet1
	// todo 遍历所有sheet
	rows := tool.GetExcelRows(fileName, "sheet1")

	var mapSlice []map[string]interface{}
	switch u.UploadType {

	case "user":

		users := tool.RowsToStrct[model.User](rows, fieldIdxMap)
		for _, user := range users {
			mapSlice = append(mapSlice, tool.StructToMap(user))
		}
		// 批量插入user数据
		defaultUserModel := service.NewDefaultUserModel()
		if err := defaultUserModel.CreateUsers(mapSlice); err != nil {
			result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
			return
		}
		result.JsonRsp(c, nil, nil)
		return
	case "post":

		posts := tool.RowsToStrct[model.Post](rows, fieldIdxMap)
		for _, post := range posts {
			mapSlice = append(mapSlice, tool.StructToMap(post))
		}
		// todo 批量插入post数据
		result.JsonRsp(c, nil, nil)
		return
	}

}
